import React from 'react';
import { Card, Table, Button, Input, Form, Space, Modal, DatePicker, Select, Radio, Row, Col, Drawer, message } from 'antd';
import dayjs from 'dayjs';

// 优惠券（模仿 admin-web 的 Coupons.vue）
export default function Coupons() {
  // 左侧新增表单
  const [couponsForm] = Form.useForm();
  const [couponsmode, setCouponsmode] = React.useState([
    { id: 1, label: '满减（固定金额）', value: 1 },
    { id: 2, label: '折扣（百分比）', value: 2 },
  ]);
  const [couponsState, setCouponsState] = React.useState([
    { id: 0, label: '未使用', value: 0 },
    { id: 1, label: '已使用', value: 1 },
  ]);

  const [formValues, setFormValues] = React.useState({
    name: '',
    reachPrice: '',
    mode: '',
    price: '',
    exTime: '',
    num: '',
    couponCodeFlag: false,
    couponCode: '',
  });

  // 右侧列表与搜索
  const [searchForm] = Form.useForm();
  const [search, setSearch] = React.useState({ name: '' });
  const [loading, setLoading] = React.useState(false);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);

  const [productList, setProductList] = React.useState(() => ([
    { id: 1, name: '中秋满减券', reachPrice: 50, mode: 1, price: 10, createTime: '2025-09-01 10:00', exTime: '2025-10-01 00:00', num: 100, overNum: 60 },
    { id: 2, name: '国庆折扣券', reachPrice: 100, mode: 2, price: 80, createTime: '2025-09-20 12:00', exTime: '2025-10-08 00:00', num: 200, overNum: 120 },
  ]));

  // 券码 Drawer
  const [showDrawer, setShowDrawer] = React.useState(false);
  const [codeData, setCodeData] = React.useState([
    { code: 'CODE-001', isUse: 0 },
    { code: 'CODE-002', isUse: 1 },
    { code: 'CODE-003', isUse: 0 },
  ]);
  const [codePageIndex, setCodePageIndex] = React.useState(1);
  const [codePageSize, setCodePageSize] = React.useState(10);
  const [codeTotal, setCodeTotal] = React.useState(3);
  const [showTitle, setShowTitle] = React.useState('查看券码');

  const filtered = React.useMemo(() => {
    let data = productList;
    if (search.name) data = data.filter(i => String(i.name).includes(search.name));
    return data;
  }, [productList, search]);

  const pageData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  const columns = [
    { title: '优惠券名称', dataIndex: 'name', width: 200, align: 'center' },
    { title: '满减金额（门槛）', dataIndex: 'reachPrice', width: 150, align: 'center' },
    {
      title: '优惠类型', dataIndex: 'mode', width: 160, align: 'center',
      render: (mode) => couponsmode.find(m => m.value === mode)?.label || mode
    },
    { title: '优惠值', dataIndex: 'price', width: 140, align: 'center' },
    { title: '创建时间', dataIndex: 'createTime', width: 160, align: 'center' },
    { title: '到期时间', dataIndex: 'exTime', width: 160, align: 'center' },
    { title: '发放数量', dataIndex: 'num', width: 140, align: 'center' },
    { title: '剩余数量', dataIndex: 'overNum', width: 170, align: 'center' },
    {
      title: '操作', fixed: 'right', width: 180, align: 'center',
      render: (_, row) => (
        <Space>
          <Button size="small" onClick={() => showCouponCode(row)}>查看券码</Button>
          <Button size="small" danger onClick={() => delCoupon(row)}>删除</Button>
        </Space>
      )
    },
  ];

  // 左侧提交
  const submitForm = async () => {
    const values = await couponsForm.validateFields();
    // 组装优惠券记录
    const newItem = {
      id: Math.max(0, ...productList.map(i => i.id)) + 1,
      name: values.name,
      reachPrice: Number(values.reachPrice || 0),
      mode: values.mode,
      price: Number(values.price || 0),
      exTime: values.exTime ? values.exTime.format('YYYY-MM-DD HH:mm:ss') : '',
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      num: Number(values.num || 0),
      overNum: Number(values.num || 0),
    };
    setProductList(prev => [newItem, ...prev]);
    message.success('优惠券已添加');
    couponsForm.resetFields();
  };

  // 右侧搜索
  const onSearchSubmit = async () => {
    const values = await searchForm.validateFields();
    setSearch(values);
    setPageIndex(1);
  };
  const resetSearch = () => {
    searchForm.resetFields();
    setSearch({ name: '' });
    setPageIndex(1);
  };

  // 查看券码
  const showCouponCode = (row) => {
    setShowTitle(`查看券码 - ${row.name}`);
    setShowDrawer(true);
    // 在真实接口中，根据 row.id 拉取券码分页数据
    setCodePageIndex(1);
  };
  const funcState = (isUse) => couponsState.find(s => s.value === Number(isUse))?.label || isUse;

  const delCoupon = (row) => {
    setProductList(prev => prev.filter(i => i.id !== row.id));
    message.success('删除成功');
  };

  return (
    <div className="product" style={{ display: 'grid', gap: 16 }}>
      <Row gutter={16}>
        {/* 左侧新增优惠券 */}
        <Col span={6}>
          <Card style={{ height: 749, borderRadius: 10 }}>
            <Form form={couponsForm} layout="vertical">
              <Form.Item label="优惠券名称" name="name" rules={[{ required: true, message: '请输入优惠券名称' }]}> 
                <Input placeholder="请输入优惠券名称" />
              </Form.Item>
              <Form.Item label="满减金额（门槛）" name="reachPrice" rules={[{ required: true, message: '请输入满减门槛金额' }]}> 
                <Input type="number" placeholder="满减门槛金额" />
              </Form.Item>
              <Form.Item label="优惠类型" name="mode" rules={[{ required: true, message: '请选择优惠类型' }]}> 
                <Select placeholder="请选择优惠类型" options={couponsmode.map(m => ({ label: m.label, value: m.value }))} />
              </Form.Item>
              {/* 金额或折扣百分比 */}
              <Form.Item noStyle shouldUpdate={(prev, curr) => prev.mode !== curr.mode}>
                {({ getFieldValue }) => {
                  const mode = getFieldValue('mode');
                  const label = mode === 2 ? '折扣百分比' : '优惠金额';
                  const placeholder = mode === 2 ? '请输入折扣百分比（0-100）' : '请输入优惠金额';
                  return (
                    <Form.Item label={label} name="price" rules={[{ required: true, message: placeholder }]}> 
                      <Input type="number" placeholder={placeholder} />
                    </Form.Item>
                  );
                }}
              </Form.Item>
              <Form.Item label="有效时长（到期时间）" name="exTime"> 
                <DatePicker showTime style={{ width: '100%' }} placeholder="请选择到期时间" />
              </Form.Item>
              <Form.Item label="发放数量" name="num" rules={[{ required: true, message: '请输入发放数量' }]}> 
                <Input type="number" placeholder="发放数量" />
              </Form.Item>
              <Form.Item label="是否生成兑换码" name="couponCodeFlag" initialValue={false}> 
                <Radio.Group>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item noStyle shouldUpdate={(prev, curr) => prev.couponCodeFlag !== curr.couponCodeFlag}>
                {({ getFieldValue }) => !getFieldValue('couponCodeFlag') && (
                  <Form.Item label="兑换码" name="couponCode"> 
                    <Input placeholder="请输入兑换码" />
                  </Form.Item>
                )}
              </Form.Item>
              <Form.Item>
                <Button type="primary" onClick={submitForm} style={{ marginTop: 8 }}>添加</Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>

        {/* 右侧优惠券列表 */}
        <Col span={18}>
          <div className="el-search vue-top-padding" style={{ marginBottom: 12 }}>
            <div className="el-left" style={{ display: 'inline-block' }}>
              <Button icon={<span className="anticon">🧾</span>} onClick={() => message.info('导出（模拟）')} size="small">导出</Button>
            </div>
            <div className="el-right" style={{ float: 'right' }}>
              <Form form={searchForm} layout="inline" initialValues={search} size="small" style={{ display: 'flex', gap: 8 }}>
                <Form.Item name="name" style={{ marginBottom: 0 }}>
                  <Input placeholder="优惠券名称" />
                </Form.Item>
                <Form.Item style={{ marginBottom: 0 }}>
                  <Space>
                    <Button type="primary" onClick={onSearchSubmit} icon={<span className="anticon">🔍</span>}>搜索</Button>
                    <Button onClick={resetSearch} icon={<span className="anticon">♻️</span>}>重置</Button>
                  </Space>
                </Form.Item>
              </Form>
            </div>
          </div>

          <Card variant="borderless">
            <Table
              rowKey={(r) => r.id}
              loading={loading}
              dataSource={pageData}
              columns={columns}
              pagination={{
                current: pageIndex,
                pageSize,
                total: filtered.length,
                onChange: (pi) => setPageIndex(pi),
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* 查看券码 Drawer */}
      <Drawer title={showTitle} open={showDrawer} onClose={() => setShowDrawer(false)} placement="right" width={420}>
        <div style={{ marginBottom: 12 }}>
          <Button icon={<span className="anticon">🧾</span>} onClick={() => message.info('导出券码（模拟）')} size="small">导出券码</Button>
        </div>
        <Table
          rowKey={(r) => r.code}
          dataSource={codeData}
          pagination={{
            current: codePageIndex,
            pageSize: codePageSize,
            total: codeTotal,
            onChange: (pi) => setCodePageIndex(pi),
          }}
          columns={[
            { title: '兑换码', dataIndex: 'code' },
            { title: '状态', dataIndex: 'isUse', render: (v) => funcState(v) },
          ]}
        />
      </Drawer>
    </div>
  );
}